package com.zhy.learning.demo.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest2 {

    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        int n = 10;
        Thread[] threads = new Thread[n];
        Thread[] threadsForWaits = new Thread[n];
        for (int i = 0; i < n; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " nowait get lock");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.unlock();
                }
            });
        }

        for (int i = 0; i < n; i++) {
            threadsForWaits[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " wait first get lock");
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " wait second get lock");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.unlock();
                }
            });
        }

        for (int i = 0; i < n; i++) {
            threadsForWaits[i].start();
            Thread.sleep(200);
        }

        lock.lock();
        for (int i = 0; i < n; i++) {
            threads[i].start();
            Thread.sleep(200);
        }
        for (int i = 0; i < 4; i++) {
            condition.signal();
        }
        Thread.sleep(200);
        lock.unlock();

        for (int i = 0; i < n; i++) {
            threads[i].join();
        }

        for (int i = 0; i < n; i++) {
            threadsForWaits[i].join();
        }
    }
}
